package com.cloudwise.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2021/2/23 15:10
 * @description：登录验证过滤器
 * @modified By：
 * @version: 1.0
 */
//@WebFilter(urlPatterns = "/*")
public class LoginFilter  implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断session中是否含有person_id，如果有，就是合法用户，没有非法用户，直接滚回登录页面
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        System.out.println("请求地址："+requestURI);
        Object personId = session.getAttribute("person_id");
        //包含login关键字，或者session中包含person_id 需要放行
        if(personId!=null||requestURI.contains("login")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else
        {
            //滚回登录页面
            response.sendRedirect("login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
